package cd826dong.cloud.zuul.filter;

import cd826dong.cloud.zuul.config.ServiceConfig;

import com.netflix.zuul.ZuulFilter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class JWTTokenFilter extends ZuulFilter {

    @Autowired
    private FilterUtils filterUtils;

    @Autowired
    private ServiceConfig serviceConfig;


    @Override
    public String filterType() {
        return FilterUtils.PRE_FILTER_TYPE;
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() {
		System.out.println("JWTTokenFilter执行成功");
		parseJWTToken();
        return null;
    }

    //解析jwt token信息
    private void parseJWTToken(){
        if(null == filterUtils.getAuthToken()){
            return;
        }

        String authToken = filterUtils.getAuthToken().replaceAll("bearer ","");
        try {
            Claims claims = Jwts.parser().setSigningKey(serviceConfig.getJwtSigningKey().getBytes("UTF-8"))
                                .parseClaimsJws(authToken).getBody();

            filterUtils.setShopId((String)claims.get("shopId"));
            filterUtils.setUserId((String)claims.get("user_name"));
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
